package com.hdoit.apollo.web.shop.controllers;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.common.enums.billing.PayState;
import com.hdoit.apollo.logical.common.enums.shop.PayObject;
import com.hdoit.apollo.logical.common.enums.shop.PaymentState;
import com.hdoit.apollo.logical.purchase.mapper.PurchaseMapper;
import com.hdoit.apollo.logical.purchase.model.Purchase;
import com.hdoit.apollo.logical.purchase.service.IPurchaseService;
import com.hdoit.apollo.logical.shop.model.Payment;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.service.IPaymentService;
import com.hdoit.apollo.logical.viewmodel.purchase.PurchaseSearch;
import com.hdoit.apollo.logical.viewmodel.shop.PayStat;
import com.hdoit.apollo.logical.viewmodel.shop.PaymentSearch;
import com.tennetcn.authority.component.web.ActionResult;
import com.tennetcn.authority.component.web.BaseController;
import com.tennetcn.authority.component.web.ErrorResult;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;

/**
 * @author      tancongzhu
 * @email       
 * @createtime  2018年06月01日 16:21:38
 * @comment
 */
@Controller
@RequestMapping(value = "/shop/payForPurchase/")
public class PayForPurchaseController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/shop/payForPurchase/";
    }

    @Autowired
    private IPaymentService paymentService;
    
    @Autowired
    private IPurchaseService purchaseService;
    
    @Autowired
    private PurchaseMapper purchaseMapper;

    private final String indexViewName="index";
    
    private final String otherViewName="other";
    
    private final String tabIndexViewName="tabIndex";
    private final String outputViewName="output";
    
    private final String otherOutputViewName="otherOutput";
    
    private final String detailedViewName="paymentDetailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,PurchaseSearch search,boolean ajaxPost){

    	PayStat stat=purchaseMapper.queryPayStat(search);
    	
        pagerModel.setTotalAmount(purchaseService.queryCountMP(search));
        List<Purchase> purchases= purchaseService.queryListMP(search,pagerModel);

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("purchases", purchases);
        model.addAttribute("purchaseSearch", search);
        model.addAttribute("stat", stat);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }
    
    
    @RequestMapping(value = otherViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String other(Model model,PagerModel pagerModel,PaymentSearch search,boolean ajaxPost){

    	 pagerModel.setTotalAmount(paymentService.queryCountMPForPurchase(search));
         List<Payment> payments= paymentService.queryListMPForPurchase(search,pagerModel);

         model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
         model.addAttribute("payments", payments);
         model.addAttribute("paymentSearch", search);


         if(ajaxPost){
             return view(otherOutputViewName);
         }

         return view(otherViewName);
    }
    
    @RequestMapping(value = tabIndexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String tabIndex(Model model,PagerModel pagerModel,PaymentSearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(paymentService.queryCountMP(search));
        List<Payment> payments= paymentService.queryListMP(search,pagerModel);

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("payments", payments);
        model.addAttribute("paymentSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(tabIndexViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String paymentDetailed(Model model,String key,String purchaseId){
        Payment payment=new Payment();
        
        Purchase purchase=new Purchase();
        System.err.println(purchaseId+"humaoshu");
        
        if (!StringUtils.isEmpty(purchaseId)) {
        	purchase=purchaseService.queryModelByKey(purchaseId);
		}                
        payment.setSupplierId(purchase.getSupplierId());
    	payment.setPurchaseId(purchaseId);

        model.addAttribute("payment", payment);
        model.addAttribute("purchase", purchase);
        return view(detailedViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,Payment payment,String purchaseId){
    	
    	Purchase purchase=new Purchase();
    	purchase=purchaseService.queryModelByKey(purchaseId);
    	
        if(StringUtils.isEmpty(payment.getPaymentId())){
            payment.setPaymentId(CommonUtils.getKeyId());
            payment.setCreateDate(DateUtils.getCurrent());
            payment.setDeleteMark(YesOrNoInteger.no);
            payment.setCreateUserId(getLoginModel().getLoginId());
            payment.setCreateUserName(getLoginModel().getLoginName());
            payment.setPaymentState(PaymentState.payment);
            payment.setPayObject(PayObject.supplier);
            payment.setModelStatus(ModelStatus.add);
            Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
            payment.setShopId(shop.getShopId());
            
            purchase.setHavePayMoney(purchase.getHavePayMoney()+payment.getAmount());
            
            if (purchase.getHavePayMoney().equals(purchase.getPurchaseMoney()+purchase.getOtherMoney())) {
            	purchase.setPayState(PayState.paid);
			}else if (purchase.getHavePayMoney()<purchase.getPurchaseMoney()+purchase.getOtherMoney()) {
				purchase.setPayState(PayState.portion);
			}
            
            
            purchase.setModifyDate(DateUtils.getCurrent());
            purchase.setModifyUserId(getLoginModel().getLoginId());
            purchase.setModifyUserName(getLoginModel().getLoginName());
            purchase.setModelStatus(ModelStatus.update);
            
        }else{
        	payment.setModifyDate(DateUtils.getCurrent());          
        	payment.setModifyUserId(getLoginModel().getLoginId());
        	payment.setModifyUserName(getLoginModel().getLoginName());
        	payment.setModelStatus(ModelStatus.update);
        }

        ActionResult actionResult;
     
        if(paymentService.applyChange(payment)&&purchaseService.applyChange(purchase)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("payment", payment);
       // model.addAttribute("purchase", purchase);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(paymentService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
}